<?php

namespace app\index\controller;
use think\Db;

class Login extends \think\Controller
{
    private function SendActiveMail($username,$qq,$name,$ActiveCode)   //发送激活邮件
    {

        $tomail=$qq.'@qq.com';
        $body= (new \think\Request)->domain().'/Index/Reg/Verify.html?qq='.$qq.'&ActiveCode='.$ActiveCode;
        $body="亲爱的".$name."同学，你已经完成了湖工志愿平台的注册，您的账号为<br>\n".$username."<br>\n，接下来需要您来激活以确认你是真人，请点击以下链接激活：\n<br><a href='".$body."'>".$body."</a>";
        send_mail($tomail,$name,'注册成功！请激活',$body);
    }

    public function login() //登录页面显示
    {
        //20210914 更新了判断登录状态并登录
        if (!empty(cookie('SafeCode')))
        {
            $this->redirect('Home/Home/index');
        }
        return $this->fetch('index/login');
    }

    public function LoginJson() //登录状态
    {


        if (input('post.name')=='')
            return json(['result'=>'error','msg'=>'请输入账号']);
        if (input('post.password')=='')
            return json(['result'=>'error','msg'=>'请输入密码']);

        $user=Db::name('users')->where(['username'=>input('post.name'),'password'=>md5(input('post.password'))])->find();

        if (!empty($user))
        {
            if($user['active']==0){
                $ActiveCode=GetRandStr(20);
                Db::name('users')->where('qq',input('post.qq'))->update(['ActiveCode'=>$ActiveCode]);
                $this->SendActiveMail($user['username'],$user['qq'],$user['name'],$ActiveCode);
                return json(['result'=>'error','msg'=>'账号还未激活，请重新前往邮箱激活']);
            }else{
                $SafeCode=GetRandStr(20);
                Db::name('users')->where(['username'=>input('post.name'),'password'=>md5(input('post.password'))])->update(['SafeCode'=>$SafeCode]);

                Monitor('登录了!',$SafeCode);

                return json(['result'=>'success','SafeCode'=>$SafeCode]);


            }


        }else{
            return json(['result'=>'error','msg'=>'用户名或密码错误']);
        }

    }
}
